import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NzMessageService, NzModalRef, UploadFile,NzModalService } from 'ng-zorro-antd';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { SFSchema,SFDateWidgetSchema, SFUISchema, SFComponent } from '@delon/form';
import * as $ from 'jquery';
import { Base64Service } from '@core/services/base64.service';
import { PersonRoomsComponent } from '../person-rooms/person-rooms.component';
import { format } from 'date-fns'
import { FormBuilder, FormGroup } from '@angular/forms';
import { TakephotoComponent } from '@shared/components/takephoto/takephoto.component';


@Component({
  selector: 'app-house-manage-person-add',
  templateUrl: './person-add.component.html',
})
export class HouseManagePersonAddComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf: SFComponent;
  @Input() roomId:string;
  @Input() roomNumber:string;
  showForm=false;
  param:any
  show=false;
  validateForm!: FormGroup;
  avatarUrl:string = "";
  previewVisible = false;
  previewImage: string | undefined = '';
  index:number=0;//判断人员是否有租房信息 0代表没有租房信息 1反之
  phoneList:any[]=[];
  has:boolean=false;
  maxSize:number=100 * 1024;//图片最大为100kb
  maxWidth:number=640;
  maxHeight:number=480;
  isAllow:boolean=true;//图片是否超出限制
  schema: SFSchema = {
    properties: {
      infoPeopleType: {
        type: 'string',
        title: '人员类别',
        enum:[
       
        ],
        ui:{
          widget:"select",
          grid: {span: 8}
        }
      },
      infoName: {
        type: 'string',
        title: '姓名',
        ui:{
          grid: {span: 8}
        }
      },
      infoSex: {
        type: 'string',
        title: '性别',
        enum:[
          {
            label:"男",
            value:1
          },
          {
            label:"女",
            value:0
          }
        ],
        ui:{
          widget:"select",
          grid: {span: 8}
        }
      },
      idCardNo :{
        type: 'string',
        title: '身份证号',
        ui:{
          grid: {span: 8}
        }
      },
      infoBirthday :{
        type: 'string',
        title: '出生日期',
        // format: 'date',
        ui:{
          grid: {span: 8},
          widget:"date",
          format:'YYYY-MM-DD',
          liveValidate:false
        }
      },
      infoNationName :{
        type:'string',
        title:'民族',
        ui:{
          grid: {span: 8}
        }
      },
      papersAddress: {
        type:'string',
        title:'户籍地址',
        ui:{
          grid: {span: 8}
        }
      },
      papersAuthority: {
        type:'string',
        title:'发证机关',
        ui:{
          grid: {span: 8}
        }
      },
      papersValidBegin :{
        type: 'string',
        title: '身份证有效起期',
        // format:'date',
        ui:{
          grid: {span: 8},
          widget:'date',
          format:'YYYY-MM-DD',
          liveValidate:false
        } as SFDateWidgetSchema
      },
      papersValidStop :{
        type: 'string',
        title: '身份证到期',
        // format:'date',
        ui:{
          grid: {span: 8},
          widget:'date',
          format:'YYYY-MM-DD',
          liveValidate:false
        } as SFDateWidgetSchema
      },
      infoMobile: {
        type: 'string',
        title: '手机号',
        ui:{
          grid: {span: 8}
        }
      },
      beginTime :{
        type: 'string',
        title: '入住日期',
        // format:'date',
        ui:{
          grid: {span: 8},
          widget:'date',
          format:'YYYY-MM-DD',
          liveValidate:false 
        } as SFDateWidgetSchema
      },
      endTime :{
        type: 'string',
        title: '离开日期',
        // format:'date',
        ui:{
          grid: {span: 8},
          widget:'date',
          format:'YYYY-MM-DD',
          liveValidate:false 
        } as SFDateWidgetSchema
      },
      // deviceFile: {
      //   type:'string',
      //   title:'备注',
      //   ui:{
      //     grid: {span: 8}
      //   }
      // },
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      },
    },
    required: ["deviceIp","infoName","infoSex","idCardNo","infoNationName","papersAddress","papersAuthority","infoBirthday","papersValidBegin","papersValidStop","beginTime","endTime"]
  }
  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: UploadFile }){
    console.log(info);
    //判断图片是否超出1M
   // this.testMaxSize(info.file);
    console.log(this.isAllow)
    // if(this.isAllow){//未超出1M
    //   this.getBase64(info.file!.originFileObj!, (img: string) => {
    //     this.avatarUrl = img;
    //     this.show=true;
    //   });
    // }else{//超出1M,压缩图片
    //   this.getBase64(info.file!.originFileObj!, (img: string) => {
    //     let imgObj=new Image();
    //     imgObj.src=img;
    //     imgObj.onload=()=>{
    //       const { width:originWidth,height:originHeight } = imgObj;
    //       console.log(originHeight,originWidth);
    //       this.compressImg(originWidth,originHeight,imgObj);
    //     }
    //   });
    // }
    this.getBase64(info.file!.originFileObj!, (img: string) => {
      let imgObj=new Image();
      imgObj.src=img;
      imgObj.onload=()=>{
        const { width:originWidth,height:originHeight } = imgObj;
        console.log(originHeight,originWidth);
        this.compressImg(originWidth,originHeight,imgObj);
      }
    });
   
  }

  //等比例缩放，canvas压缩图片
  compressImg(originWidth:number,originHeight:number,img){
    let targetWidth=originWidth;
    let targetHeight=originHeight;
    // 等比例计算超过最大限制时缩放后的图片尺寸
    if (originWidth > this.maxWidth || originHeight > this.maxHeight) {
      if (originWidth / originHeight > 1) {
      // 宽图片
      targetWidth = this.maxWidth
      targetHeight = Math.round(this.maxWidth * (originHeight / originWidth))
      } else {
      // 高图片
      targetHeight = this.maxHeight
      targetWidth = Math.round(this.maxHeight * (originWidth / originHeight))
      }
    }

    console.log(targetHeight,targetWidth);
    // 创建画布
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    
    // 设置宽高度为等同于要压缩图片的尺寸
    canvas.width = targetWidth
    canvas.height = targetHeight
    context.clearRect(0, 0, targetWidth, targetHeight)
    //将img绘制到画布上
    context.drawImage(img, 0, 0, targetWidth, targetHeight)
    let base64=canvas.toDataURL("image/jpeg",0.8);
    this.avatarUrl = base64;
    this.show=true;
  }

  // //判断图片大小是否超出限制
  // testMaxSize(file){
  //   if(file){
  //     let size=file.size;//这里读到的是字节数
  //     let max_size=this.maxSize * 1024 ; //转化为字节
  //     if(size > max_size){
  //       //this.msg.error("图片最大为2M,超出大小!");
  //       this.isAllow=false;
  //     }else{
  //       this.isAllow=true;
  //     }
  //   }
  // }
 
  formSubmit(data) {
    console.log(data)
    if(!data.infoBirthday){
      this.msg.error("出生日期不能为空")
      return
    }
    if(!data.papersValidBegin){
      this.msg.error("身份证有效期不能为空")
      return
    }
    if(!data.papersValidStop){
      this.msg.error("身份证有效期不能为空")
      return
    }
    if(!data.beginTime){
      this.msg.error("入住日期不能为空")
      return
    }
    if(!data.endTime){
      this.msg.error("离开日期不能为空")
      return
    }
    let self=this;
    if(this.index == 0){//代表是第一次点击确定   查询是否有租房信息
      new Promise((resolve:any)=>{
        this.http.post('/core/room/findPersonAndRoom', {papersNumber:data.idCardNo}).subscribe((res:any) => {
          console.log(res)
          if (res.status == '200' && res.data.length > 0) {
            let list=res.data;
            self.phoneList=[];
            for(let item of list){
              self.phoneList.push(item.mobile);
            }
            self.index = 1;
            const modal = this.modal.create({
              nzTitle: "提示",
              nzContent: PersonRoomsComponent,
              nzWidth: '70%',
              nzComponentParams: {
                list
              },
              nzFooter:null
            })
          }else{
            self.index=2;
          }
          resolve();
        })
      }).then(()=>{
        console.log("直接提交")
        if(self.index == 2){//代表查不到租房信息，直接提交数据
          self.submitData(data);
        }
      })
      return;
    }else if(this.index == 1){//有租房信息，匹配手机号是否相同，不相同的话提示手机号与之前的不一致，是否继续提交，点确定直接提交接口
      let i=this.phoneList.findIndex(item => item == data.infoMobile );
      if(data.infoMobile == undefined || data.infoMobile == ""){
        i=2;
      }
      if(i == -1){//表示手机号与之前录入的不相同
        this.modal.create({
          nzTitle: '提示',
          nzContent: '您填写的手机号与之前录入的手机号不一致，点击确定继续添加！',
          nzWidth: 300,
          nzOnOk(){
            self.submitData(data);
          }
        })
      }else{
        self.submitData(data);
      }
      return;
    }
   self.submitData(data);
}

//提交数据
submitData(data:object){
  
  if(this.avatarUrl.indexOf("data:image") == -1){
    this.avatarUrl=this.base64.getDefaultBase64();
  }
  const body: any = data;
  body.idCardPic=this.avatarUrl.replace(/^data:image\/\w+;base64,/, '');
  body.papersType=1;
  body.roomId=this.roomId;
  let arr=Object.keys(body);
  if(arr.findIndex(item => item == "infoMobile") == -1){
    body.infoMobile="";
  }
  console.log(body);
this.http.post(this.api.house.peopleRegister.url,body).subscribe((res:any) => {
  console.log(res)
  if (res.status === '200') {
    this.msg.success('操作成功');
    this.modalRef.destroy('ok');
  } else {
    this.msg.error(res.message)
  }
})
}

//拍照
takePhoto() {
  this.modalRef = this.modal.create({
    nzTitle:  '拍照',
    nzContent: TakephotoComponent,
    nzWidth: 600,
    nzFooter:null
  })
  this.modalRef.afterClose.subscribe(res=>{
    if(res){
      this.avatarUrl = res;
      this.show=true;
    }else{
      const modalInstance = this.modalRef.getContentComponent(); // 获取模态框实例
      if(modalInstance.stream){
        modalInstance.stream.getTracks()[0].stop()
      }
    }
  })
}


constructor(
  private api: ApiService,
  private http: HttpClient,
  private msg: NzMessageService,
  private modalRef: NzModalRef,
  private base64: Base64Service,
  private modal: NzModalService,
  private fb:FormBuilder
) { }


//读取身份证信息
readIdCard(){
  let that=this;
  $.ajax({
    url:"http://127.0.0.1:18889/api/readCard",
    type:"post",
    success:function(data){
      console.log(data);
      let arr=JSON.parse(data);
      if(arr.resultFlag == -1){
        that.msg.error(arr.errorMsg);
      }else if(arr.resultFlag == 0){
          that.param={
            "infoName":arr.resultContent.partyName,
            "infoSex":arr.resultContent.gender,
            "idCardNo":arr.resultContent.certNumber,
            "infoBirthday":that.getDate(arr.resultContent.bornDay),
            "infoNationName":arr.resultContent.nation,
            "papersAddress":arr.resultContent.certAddress,
            "papersAuthority":arr.resultContent.certOrg,
            "papersValidBegin":that.getDate(arr.resultContent.effDate),
            "papersValidStop":that.getDate(arr.resultContent.expDate)
          };
          that.avatarUrl="data:image/jpg;base64,"+arr.resultContent.identityPic;
          that.show=true;
      }
    }
  })
}


  ngOnInit(): void {
    this.showForm=true
    this.validateForm = this.fb.group({
      btime:new Date(),
      etime:new Date(),
      cbtime:new Date(),
      cetime:new Date(),
      lbtime:new Date(),
      letime:new Date(),
      // rangePickerTime: [[new Date(this.param.cardUsingStartTime),new Date(this.param.cardUsingEndTime)]]
    });
    this.connect();
  }

  ngAfterViewInit(){
    if(this.roomNumber == "0"){//应急房
      this.schema.properties.infoPeopleType.enum=[
        {
          label:"保安",
          value:4
        },
        {
          label:"保洁",
          value:5
        },
        {
          label:"物业人员",
          value:6
        },
        {
          label:"网格员",
          value:7
        },
        {
          label:"片警",
          value:8
        }
      ]
    }else{
      this.schema.properties.infoPeopleType.enum=[
        {
          label:"租客",
          value:3
        },
        {
          label:"业主",
          value:1
        }
      ]
    }
    this.sf.refreshSchema();
  }
  connect(){
    $.ajax({
      url:"http://127.0.0.1:18889/api/connect",
      type:"post",
      success:function(data){
        console.log(data);
      }
    })
  }

  //获取标准日期格式
  getDate(str:string){
    const year=str.substring(0,4);
    const month=str.substring(4,6);
    const date=str.substring(6,8);
    return year+"-"+month+"-"+date;
  }
}
